<?php
/**
 *  💡 免责声明：本软件不得用于商业用途，仅做学习交流
 *  ⚠️ 权利声明：本软件由版权人提供产品技术支持
 *  📅 项目编号：NX2025-0135
 */
namespace App\Api\Controllers\Auths;

use App\Api\BaseApi;
use App\Models\BeanPackages;
use App\Models\TradingHall;
use App\Models\UserBeanPackages;
use App\Service\Setting\BeanSettingService;
use App\Service\Setting\WithdrawCashSettingService;
use App\Service\Statistics\StatisticsService;
use App\Service\Trade\TradeService;
use App\Service\User\BeanAccountService;
use App\Service\User\WalletAccountService;
use Illuminate\Support\Facades\DB;

class BeanApi extends BaseApi
{
    public function purchaseBeanPackage()
    {
        $request = self::validate([
            'package_id' => 'required',
        ]);
        if (UserBeanPackages::query()->where('user_id',self::UserId())->exists()) {
            return responses('只能购买一次该礼包',7);
        }
        $package = BeanPackages::query()
           ->find($request->get('package_id'));

        if (! $package) {
            return responses('该礼包不存在！', 7);
        }
        if ($package->stock < 1) {
            return responses('该礼包已售完或已过期！', 7);
        }

        $user = self::UserModel(['address']);
        if (blank($user->address)) {
            return responses('请绑定收货地址！', 7);
        }
        $ws = WalletAccountService::make()->consumption(self::UserId(),$package->price,'购买初始礼包,消费:'.$package->price);
        if ($ws){
            UserBeanPackages::query()->Create([
                'user_id' => self::UserId(),
                'package_id' => $package->id,
                'total_beans' => $package->total_amount,
                'remaining_beans' => $package->total_amount,
                'daily_release_rate' =>0,
                'release_days' => $package->total_days,
                'purchase_amount' => $package->price,
                'status' => 0,
                'user_address_id' => $user->address->id,
            ]);
            BeanAccountService::make()->recharge(self::UserId(),$package->total_amount,'购买初始礼包获得通证:'.$package->total_amount);
            return responses('礼包购买成功');
        }
        return responses('余额不足',7);
    }

    public function getMyPackage()
    {
        $res = UserBeanPackages::query()->where('user_id',self::UserId())->get();
        return responses($res);
    }
    public function getBeanPrice()
    {
        return responses(BeanSettingService::make()->getSetting('PRICE'));
    }

    public function sellBean()
    {
        $request = self::validate([
            'amount' => 'required|min:1',
            'trading_hall_id' => 'required|exists:trading_halls,id',
        ]);
        $userModel = self::UserModel();
        $this->transaction_password($userModel);
        $amount = $request->get('amount');
        $trading_hall_id = $request->get('trading_hall_id');
        //指导价的贡献值
        $pointPrice = StatisticsService::make()->getNowPrice();
        $totalValue = bcmul($amount, $pointPrice, 2);
        if ($userModel->contribution_value < $totalValue) {
            return responses('贡献值不足，售出失败,需要贡献值:' . $totalValue, 7);
        }
        //pre_sale
        $res = TradeService::make()->sell($trading_hall_id, $amount, $userModel);
        if ($res['flag']) {
            $userModel->contribution_value -= $amount;
            $userModel->save();
            return responses($res['msg']);
        }
        return responses($res['msg'], 7);
    }

    public function buyBean()
    {
        $request = self::validate([
            'amount' => 'required|min:1',
            'price' => 'required|min:0.1',
        ]);
        //TODO 限制买入数量
        $userModel = self::UserModel(['userLevel']);
        $amount = $request->get('amount');
        $price = $request->get('price');

        $this->transaction_password($userModel);
        $setting = BeanSettingService::make()->getSetting();
        $trading_floating = $setting->get('TRADING_FLOATING');
        $nowPrice = $setting->get('PRICE');
        $contribution_value = $setting->get('CONTRIBUTION_VALUE');
        $r = bcmul($nowPrice, $trading_floating, 2);

        if ($price < (bcsub($nowPrice, $r, 2)) || $price > (bcadd($nowPrice, $r, 2))) {
            return responses(sprintf('价格超过指导价正负百分之%s', bcmul($trading_floating, 100)), 7);
        }
//        if ($userModel->contribution_value < $contribution_value) {
//            return responses('贡献值不足，求购失败', 7);
//        }
        $buy_bean = $userModel->userLevel->buy_bean ?? 0;
        if ($buy_bean == 0) {
            return responses('拼单等级不足，求购失败', 7);
        }
        if ($amount > $buy_bean) {
            return responses('超过当前拼单等级最大求购量，求购失败', 7);
        }
//        $TradingHall = TradingHall::query()
//            ->where('user_id', self::UserId())
//            ->where('status', 1)
//            ->where('type', 1)
//            ->exists();
//        if ($TradingHall){
//            return responses('已存在求购单，创建失败', 7);
//        }

        $res = TradeService::make()->buy(
            self::UserId(),
            $amount,
            $price
        );
        if ($res['flag']) {
            return responses($res['msg']);
        }

        return responses($res['msg'], 7);
    }

    public function tradingHall() //交易大厅
    {
        $res = TradingHall::with('user')
            ->where('status', 1)
            ->where('type', 1)
            ->orderByDesc('price')
            ->orderByDesc('created_at')
            ->simplePaginate(request('pageSize', 10));
        return responses($res);
    }

    public function myDeal() //我的交易
    {
        $request = self::validate([
            'type' => 'required',
            'status' => 'required',
        ]);
        $type = $request->get('type');
        $status = $request->get('status');
        $res = TradingHall::query()
            ->where('user_id', self::UserId())
            ->when($type != 0, function ($query) use ($type) {
                $query->where('type', $type);
            })->when($status != 0, function ($query) use ($status) {
                $query->where('status', $status);
            })
            ->simplePaginate(request('pageSize', 10));
        return responses($res);
    }

    public function myDealDetails() //我的交易详情
    {
        $request = self::validate([
            'id' => 'required',
        ]);
        $res = TradingHall::with(['buyTrades', 'sellTrades'])
            ->where('user_id', self::UserId())
            ->where('id', $request->get('id'))
            ->first();
        return responses($res);
    }

    public function cancelTheTransaction() //取消交易
    {
        $request = self::validate([
            'id' => 'required',
        ]);
        $this->transaction_password(self::UserModel());
        return DB::transaction(function () use ($request) {
            $res = TradingHall::with(['buyTrades', 'sellTrades'])
                ->where('user_id', self::UserId())
                ->where('id', $request->get('id'))
                ->where('type', 1)
                ->where('status', 1)
                ->lockForUpdate()
                ->first();
            if (blank($res)) {
                return responses('无效的交易!取消失败', 7);
            }
            $amount = bcsub($res->amount, $res->traded_quantity);
            if ($amount < 0) {
                return responses('剩余交易数量不足！取消失败', 7);
            }
            $money = bcmul($amount, $res->price, 2);
            $msg = sprintf('求购KC取消,求购总数:%s,成交数:%s,求购单价:%s,退回余额:%s', $res->amount, $res->traded_quantity, $res->price, $money);
            WalletAccountService::make()->recharge(
                $res->user_id,
                $money,
                $msg,
                1,
                6
            );
            $res->status = 3;
            $res->save();
            return responses($msg);
        });
    }

    public function getBeanSetting()
    {
        $data = BeanSettingService::make()->getSetting();
        return responses($data);
    }

    public function getHallSetting()
    {
        $data = WithdrawCashSettingService::make()->getSetting();
        return responses($data);
    }
}
